<?php
// 开启错误日志
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'D:/BtSoft/wwwlogs/weather_error.log');

// 记录请求信息
error_log("=== 新的请求开始 ===");
error_log("请求时间: " . date('Y-m-d H:i:s'));
error_log("请求参数: " . json_encode($_GET));

// 读取配置
$config = json_decode(file_get_contents('config.json'), true);
$platform = $config['apiPlatform'] ?? 'amap';
$amapKey = $config['amapKey'] ?? '';
$qweatherKey = $config['qweatherKey'] ?? '';
$qweatherHost = $config['qweatherHost'] ?? '';
$qweatherJwt = $config['qweatherJwt'] ?? '';
$aliyunAppCode = $config['aliyunAppCode'] ?? '';

// 记录配置信息
error_log("当前配置: " . json_encode([
    'platform' => $platform,
    'host' => $qweatherHost,
    'useJwt' => !empty($qweatherJwt)
]));

$city = $_GET['city'] ?? '';
if (!$city) {
    error_log("错误: 缺少城市参数");
    echo json_encode(['code'=>'400','msg'=>'缺少城市参数']);
    exit;
}

// 城市名适配映射
$cityMap = [
    '香港特别行政区' => '香港',
    '澳门特别行政区' => '澳门',
    '内蒙古自治区' => '呼和浩特', // 可根据实际需求调整
    '广西壮族自治区' => '南宁',
    '西藏自治区' => '拉萨',
    '宁夏回族自治区' => '银川',
    '新疆维吾尔自治区' => '乌鲁木齐',
    '北京市' => '北京',
    '天津市' => '天津',
    '上海市' => '上海',
    '重庆市' => '重庆',
    // 可继续补充
];
if (isset($cityMap[$city])) {
    error_log("城市名适配: $city => " . $cityMap[$city]);
    $city = $cityMap[$city];
}

if ($platform === 'amap') {
    // 高德天气API
    $weatherUrl = "https://restapi.amap.com/v3/weather/weatherInfo?city=" . urlencode($city) . "&key=$amapKey&extensions=all";
    $weatherRes = file_get_contents($weatherUrl);
    $weatherData = json_decode($weatherRes, true);
    if ($weatherData['status'] !== '1' || empty($weatherData['forecasts'][0])) {
        echo json_encode([
            'code' => $weatherData['infocode'] ?? '404',
            'msg' => $weatherData['info'] ?? '未找到城市或Key无效',
            'raw' => $weatherData
        ]);
        exit;
    }
    $forecast = $weatherData['forecasts'][0];
    $casts = $forecast['casts'] ?? [];
    $live = $forecast['casts'][0] ?? [];
    $result = [
        'code' => '200',
        'updateTime' => $forecast['reporttime'] ?? '',
        'now' => [
            'text' => $live['dayweather'] ?? '',
            'temp' => $live['daytemp'] ?? '',
            'humidity' => $live['humidity'] ?? '',
            'windDir' => $live['daywind'] ?? '',
            'windScale' => $live['daypower'] ?? '',
            'pressure' => '',
            'feelsLike' => '',
        ],
        'daily' => $casts,
        'hourly' => [],
    ];
    header('Content-Type: application/json');
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($platform === 'qweather') {
    // 和风天气API
    $host = $qweatherHost ?: 'devapi.qweather.com';
    $useJwt = $qweatherHost && $qweatherJwt;
    
    // 1. 获取城市ID（新版：专属Host+JWT，不用key参数）
    if ($useJwt) {
        $geoUrl = "https://$host/geo/v2/city/lookup?location=" . urlencode($city);
        $headers = [
            "Authorization: Bearer $qweatherJwt"
        ];
    } else {
        $geoUrl = "https://devapi.qweather.com/v2/city/lookup?location=" . urlencode($city) . "&key=" . $qweatherKey;
        $headers = [];
    }
    error_log("请求城市查询API: " . $geoUrl);
    $geoRes = curl_get($geoUrl, $headers);
    $geoData = json_decode($geoRes, true);
    error_log("城市查询API响应: " . json_encode($geoData));
    
    if (!$geoData || $geoData['code'] !== '200' || empty($geoData['location'][0]['id'])) {
        error_log("错误: 城市查询失败 - " . json_encode($geoData));
        echo $geoRes; // 直接输出原始响应，便于前端调试
        exit;
    }
    
    $cityId = $geoData['location'][0]['id'];
    error_log("获取到城市ID: " . $cityId);
    
    // 2. 实时天气
    if ($useJwt) {
        $nowUrl = "https://$host/v7/weather/now?location=$cityId";
        $dailyUrl = "https://$host/v7/weather/7d?location=$cityId";
        $hourlyUrl = "https://$host/v7/weather/24h?location=$cityId";
        $headers = [
            "Authorization: Bearer $qweatherJwt"
        ];
        error_log("使用JWT请求天气API: " . $nowUrl);
        
        $now = json_decode(curl_get($nowUrl, $headers), true);
        $daily = json_decode(curl_get($dailyUrl, $headers), true);
        $hourly = json_decode(curl_get($hourlyUrl, $headers), true);
        
        error_log("天气API响应: " . json_encode($now));
    } else {
        $nowUrl = "https://devapi.qweather.com/v7/weather/now?location=$cityId&key=$qweatherKey";
        $dailyUrl = "https://devapi.qweather.com/v7/weather/7d?location=$cityId&key=$qweatherKey";
        $hourlyUrl = "https://devapi.qweather.com/v7/weather/24h?location=$cityId&key=$qweatherKey";
        
        error_log("使用Key请求天气API: " . $nowUrl);
        
        $now = json_decode(curl_get($nowUrl), true);
        $daily = json_decode(curl_get($dailyUrl), true);
        $hourly = json_decode(curl_get($hourlyUrl), true);
        
        error_log("天气API响应: " . json_encode($now));
    }
    
    $result = [
        'code' => $now['code'],
        'updateTime' => $now['updateTime'] ?? '',
        'now' => $now['now'] ?? [],
        'daily' => $daily['daily'] ?? [],
        'hourly' => $hourly['hourly'] ?? [],
    ];
    error_log("最终返回数据: " . json_encode($result));
    header('Content-Type: application/json');
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($platform === 'aliyun') {
    // 验证阿里云配置
    if (empty($aliyunAppCode)) {
        error_log("错误: 阿里云AppCode未配置");
        echo json_encode(['code'=>'400','msg'=>'阿里云AppCode未配置']);
        exit;
    }
    
    // 判断输入是区划代码还是城市名
    $areaCode = '';
    if (preg_match('/^\d{6}$/', $city)) {
        $areaCode = $city;
    } else {
        // 常用城市名到区划代码映射
        $cityMap = [
            '北京' => '110000',
            '上海' => '310000',
            '广州' => '440100',
            '深圳' => '440300',
            '天津' => '120000',
            '重庆' => '500000',
            '杭州' => '330100',
            '南京' => '320100',
            '成都' => '510100',
            '西安' => '610100',
            '苏州' => '320500',
            '武汉' => '420100',
            '长沙' => '430100',
            '郑州' => '410100',
            '青岛' => '370200',
            '沈阳' => '210100',
            '大连' => '210200',
            '宁波' => '330200',
            '厦门' => '350200',
            '合肥' => '340100',
            '福州' => '350100',
            '济南' => '370100',
            '哈尔滨' => '230100',
            '长春' => '220100',
            '石家庄' => '130100',
            '南昌' => '360100',
            '昆明' => '530100',
            '南宁' => '450100',
            '海口' => '460100',
            '兰州' => '620100',
            '贵阳' => '520100',
            '太原' => '140100',
            '呼和浩特' => '150100',
            '乌鲁木齐' => '650100',
            '拉萨' => '540100',
            '香港' => '810000',
            '澳门' => '820000',
            '抚顺' => '210400',  // 添加抚顺区划代码
            // ...可继续扩展
        ];
        $areaCode = $cityMap[$city] ?? '';
        if (!$areaCode) {
            error_log("错误: 不支持的城市名 - " . $city);
            echo json_encode(['code'=>'400','msg'=>'不支持的城市名，请输入区划代码或支持的城市名']);
            exit;
        }
        error_log("城市名转换为区划代码: " . $city . " => " . $areaCode);
    }

    $type = $_GET['type'] ?? '';
    if ($type === 'now') {
        // 实时天气接口
        $host = "https://getweather.market.alicloudapi.com";
        $path = "/lundear/weather1d/query";
        $method = "GET";
        $headers = [
            "Authorization:APPCODE " . $aliyunAppCode,
            "Content-Type: application/json; charset=UTF-8"
        ];
        $querys = "areaCode=" . urlencode($areaCode);
        $url = $host . $path . "?" . $querys;
        error_log("请求阿里云实时天气API: " . $url);
        error_log("请求头: " . json_encode($headers));
        error_log("区划代码: " . $areaCode);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        error_log("HTTP状态码: " . $httpCode);
        error_log("响应头: " . substr($response, 0, $headerSize));
        error_log("响应体: " . $body);
        if(curl_errno($curl)) {
            error_log("Curl错误: " . curl_error($curl));
            echo json_encode([
                'code' => '500',
                'msg' => '请求失败: ' . curl_error($curl)
            ]);
            exit;
        }
        curl_close($curl);
        $weatherData = json_decode($body, true);
        if (!$weatherData || strval($weatherData['code']) !== '0') {
            error_log("错误: 阿里云天气API请求失败 - " . json_encode($weatherData));
            echo json_encode([
                'code' => $weatherData['code'] ?? '404',
                'msg' => $weatherData['msg'] ?? '请求失败',
                'raw' => $weatherData
            ]);
            exit;
        }
        $result = $weatherData['data'] ?? [];
        $now = $result['now'] ?? [];
        $day = $result['day'] ?? [];
        $night = $result['night'] ?? [];
        $hour1data = $result['hour1data'] ?? [];
        $formattedResult = [
            'code' => '200',
            'updateTime' => date('Y-m-d H:i:s'),
            'now' => [
                'text' => $now['weather'] ?? '',
                'temp' => $now['temp'] ?? '',
                'humidity' => $now['SD'] ?? $now['sd'] ?? '',
                'windDir' => $now['WD'] ?? '',
                'windScale' => $now['WS'] ?? '',
                'pressure' => $now['qy'] ?? $now['pressure'] ?? '',
                'feelsLike' => $now['temp'] ?? '',
            ],
            'daily' => [
                [
                    'fxDate' => $day['time'] ?? '',
                    'textDay' => $day['weather'] ?? '',
                    'textNight' => $night['weather'] ?? '',
                    'tempMax' => $day['temperature'] ?? '',
                    'tempMin' => $night['temperature'] ?? '',
                    'windDirDay' => $day['wind'] ?? '',
                    'windScaleDay' => $day['wind_pow'] ?? '',
                    'windDirNight' => $night['wind'] ?? '',
                    'windScaleNight' => $night['wind_pow'] ?? ''
                ]
            ],
            'hourly' => array_map(function($h) {
                return [
                    'fxTime' => $h['jf'] ?? '',
                    'text' => '',
                    'temp' => $h['je'] ?? '',
                ];
            }, $hour1data)
        ];
        header('Content-Type: application/json');
        echo json_encode($formattedResult, JSON_UNESCAPED_UNICODE);
        exit;
    } else {
        // 未来七天接口
        $host = "https://getweather.market.alicloudapi.com";
        $path = "/lundear/weather7d/query";
        $method = "GET";
        $headers = [
            "Authorization:APPCODE " . $aliyunAppCode,
            "Content-Type: application/json; charset=UTF-8"
        ];
        $querys = "areaCode=" . urlencode($areaCode);
        $url = $host . $path . "?" . $querys;
        error_log("请求阿里云7天天气API: " . $url);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        error_log("HTTP状态码: " . $httpCode);
        error_log("天气API响应: " . $body);
        if(curl_errno($curl)) {
            error_log("Curl错误: " . curl_error($curl));
            echo json_encode([
                'code' => '500',
                'msg' => '请求失败: ' . curl_error($curl)
            ]);
            exit;
        }
        curl_close($curl);
        $weatherData = json_decode($body, true);
        if (!$weatherData || strval($weatherData['code']) !== '0') {
            error_log("错误: 阿里云天气API请求失败 - " . json_encode($weatherData));
            echo json_encode([
                'code' => $weatherData['code'] ?? '404',
                'msg' => $weatherData['msg'] ?? '请求失败',
                'raw' => $weatherData
            ]);
            exit;
        }
        $result = $weatherData['data'] ?? [];
        // 提取d1~d7
        $dailyArr = [];
        for ($i = 1; $i <= 7; $i++) {
            $key = 'd' . $i;
            if (!isset($result[$key])) continue;
            $day = $result[$key];
            $dailyArr[] = [
                'fxDate' => $day['time'] ?? '',
                'textDay' => $day['weather'] ?? '',
                'textNight' => $day['weather'] ?? '',
                'tempMax' => $day['temperature_max'] ?? '',
                'tempMin' => $day['temperature_min'] ?? '',
                'windDirDay' => $day['wind_day'] ?? '',
                'windScaleDay' => $day['wind_pow'] ?? '',
                'windDirNight' => $day['wind_night'] ?? '',
                'windScaleNight' => $day['wind_pow'] ?? ''
            ];
        }
        // 当前天气用d1
        $d1 = $result['d1'] ?? [];
        $formattedResult = [
            'code' => '200',
            'updateTime' => date('Y-m-d H:i:s'),
            'now' => [
                'text' => $d1['weather'] ?? '',
                'temp' => $d1['temperature_max'] ?? '',
                'humidity' => '',
                'windDir' => $d1['wind_day'] ?? '',
                'windScale' => $d1['wind_pow'] ?? '',
                'pressure' => '',
                'feelsLike' => $d1['temperature_max'] ?? '',
            ],
            'daily' => $dailyArr,
            'hourly' => array_map(function($h) {
                return [
                    'fxTime' => $h['jf'] ?? '',
                    'text' => '',
                    'temp' => $h['je'] ?? '',
                ];
            }, $d1['hour1data'] ?? [])
        ];
        header('Content-Type: application/json');
        echo json_encode($formattedResult, JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// curl_get函数
function curl_get($url, $headers = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $output = curl_exec($ch);
    
    if(curl_errno($ch)) {
        error_log("Curl错误: " . curl_error($ch));
    }
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    error_log("HTTP状态码: " . $httpCode);
    
    curl_close($ch);
    return $output;
}

echo json_encode(['code'=>'400','msg'=>'不支持的平台类型']); 